<template>
  <div class="warpper">

    <div class="form" @click="isgoprolist = false">
      <el-form ref="ruleForm" :model="formData" size="mini" label-width="160px" style="width:85%">
        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="11">
            <el-form-item label="status" prop="status" style="width: 460px;">
              <template slot-scope="scope">
                <span>{{ formData.status }}</span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11" style="text-align: right;">
            <el-form-item v-if="formData.status !='approved'">
              <template slot-scope="scope">
                <el-button plain v-permission="['customerpaybackreports.update']" type="primary"
                  @click="godisable(true)" :disabled="isapproved"
                  v-if="formData.status =='pending' || formData.status =='rejection'">{{isdiable?"Edit":"Cancel Edit"}}</el-button>
                <el-button plain type="default" v-permission="['customerpaybackreports.void']"
                  @click="editstatus(id, 'voided')" :disabled="isapproved"
                  v-if="formData.status =='pending'">Voided</el-button>
                <el-button plain type="danger" v-permission="['customerpaybackreports.rejection']"
                  @click="editstatus(id, 'rejection')" :disabled="isapproved"
                  v-if="formData.status =='pending'">Rejection</el-button>
                <el-button plain type="primary" v-permission="['customerpaybackreports.auditing']"
                  @click="editstatus(id, 'approved')" :disabled="isapproved"
                  v-if="formData.status =='pending'">Auditing</el-button>
                <el-button plain type="default" @click="close()"
                  v-if="formData.status =='approved' || formData.status =='voided' || formData.status =='rejection'">Back</el-button>
              </template>
            </el-form-item>
            <el-form-item v-if="formData.status =='approved'">
              <template slot-scope="scope">
                <el-button plain type="default" @click="convertExcelToPDF()">Print Report</el-button>
                <el-button plain type="default" @click="exportData">Export to Excel</el-button>
                <el-button plain type="default" @click="close()">Back</el-button>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog title="" :visible.sync="caigou3" width="1200px" @close="onCloseDialog">
      <div class="layui-fluid layui-anim layui-anim-upbit your-background-class" id="print_body3"
        style="padding: 0; background-image: url(https://v.ttxcx.net/static/img/u1.png);width: 1200px;background-repeat: no-repeat;height: 1700px;background-size: cover;">
        <div>
          <input v-model="printform.ordernumber" class="ordernumber">
        </div>
        <div style="display: flex;padding-top: 154px;justify-content: space-between;">


          <div class="layui-row layui-col-space15" style="padding-left: 180px;">

            <div class="layui-col-md12">
              <div class="layui-card" style="width: 300px;">
                <div style="width: 100%;text-align: left;font-size: 20px;">
                  <input v-model="printform.addtime" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-weight: 100;">
                </div>
                <div style="width: 100%;text-align: left;font-size: 20px;">
                  <input type="textarea" value="GAPURA SOLUTIONSDN BHD" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 600;">
                </div>
                <div style="width: 100%;text-align: left;font-size: 20px;">
                  <input v-model="printform.attention" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 100;">
                </div>
              </div>
            </div>
          </div>

          <div class="layui-row layui-col-space15" style="padding-right: 12%;">
            <div class="layui-col-md12">
              <div class="layui-card" style="width: 300px;">
                <div style="width: 100%;text-align: left;font-size: 20px;">
                  <input v-model="printform.fax" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-weight: 100;">
                </div>
                <div style="width: 100%;text-align: left;font-size: 20px;">
                  <input type="textarea" v-model="printform.tel" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 100;">
                </div>
                <div style="width: 100%;text-align: left;font-size: 20px;">
                  <input value="1/1" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 100;">
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="layui-row layui-col-space15" style="padding-left: 190px;padding-top: 16px;">
          <div class="layui-col-md12">
            <div class="layui-card" style="width: 500px;">
              <div style="width: 100%;text-align: left;font-size: 20px;">
                <input v-model="printform.term+' '+printform.termdataday" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-weight: 100;">
              </div>
              <div style="width: 100%;text-align: left;font-size: 20px;">
                <input type="textarea" v-model="printform.leadtime" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 100;">
              </div>
              <div style="width: 100%;text-align: left;font-size: 20px;">
                <input v-model="printform.paymentterm" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 100;">
              </div>
              <div style="width: 100%;text-align: left;font-size: 20px;">
                <input v-model="printform.validityday" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 100;">
              </div>
            </div>
          </div>
        </div>



        <div style="display: flex;padding-top: 100px;justify-content: space-between;">

          <div style="padding-left: 80px;width: 1200px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 20px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p style="display: inline-block;width: 100px;">{{index+1}} </p>
              <p style="display: inline-block;width: 560px;">{{ item.ordernumber?item.ordernumber:item.refno}} /
                {{ item.customersid}}<br>{{ item.customername}}
              </p>
              <p style="display: inline-block;width: 160px;">{{ item.totalamount}}</p>
              <p style="display: inline-block;width: 72px;">{{ item.outstanding}}</p>
              <p style="display: inline-block;width: 143px;">{{ item.settleamount}}</p>
            </div>
          </div>
        </div>
      </div>

      <div class="layui-inline ipt layui-col-md12" id="wdDs"
        style="text-align:right;margin-top:20px;margin-right:60px;display: flex;align-items: center;justify-content: space-between">
        <span class="layui-btn print ipt" id="indfs"><i class="iconfont icon-font-61d" style="color: #fff;"></i></span>
        <el-button type="primary" v-print="'#print_body3'">Print</el-button>
      </div>
    </el-dialog>

    <div class="form" id="cadd" @click="isgoprolist = false">

      <el-form ref="ruleForm" :model="formData" :rules="rules" size="mini" label-width="168px" style="width:95%"
        :disabled="isdiable">

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Order Number" prop="ordernumber" style="width:460px">
              <el-input v-model="formData.ordernumber" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="Create Date" prop="created_at" style="width:460px">
              <el-date-picker v-model="formData.addtime" type="date" value-format="yyyy-MM-dd" style="width:290px;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Customer ID" prop="customerid" style="width: 460px;">
              <el-select @change="changetermc(1)" v-model="formData.customerid" placeholder="Select Customer"
                style="width:290px;" filterable remote :remote-method="remoteidMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.customerid" :value="item.customerid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Payment Date" prop="paymentdate" style="width:460px">
              <el-date-picker v-model="formData.paymentdate" type="date" value-format="yyyy-MM-dd" style="width:290px;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Customer Name" prop="customername" style="width: 460px;">
              <el-select @change="changetermc(2)" v-model="formData.customername" placeholder="Select Customer"
                style="width:290px;" filterable remote :remote-method="remoteMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.customerid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Currency" prop="currency" style="width: 460px;">
              <el-input v-model="formData.currency"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Payment Amount" prop="paymentamount" style="width: 460px;">
              <el-input v-model="formData.paymentamount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Payment Remark" prop="remark" style="width: 460px;">
              <el-input v-model="formData.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Staff" prop="staff" style="width: 460px;">
              <el-select v-model="formData.staff" placeholder="Select Staff" style="width:290px;">
                <el-option v-for="item in staff" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Rate" prop="rate" style="width: 460px;">
              <el-input v-model="formData.rate"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Total Outstanding">{{totaloutstanding.toFixed(2)}}</el-form-item>
          </el-col>
        </el-row>



        <div class="dialog-footer" style="margin-left: 170px; padding: 20px;" v-if="isNew || (isEdit && !isdiable)">

          <el-button @click="clearformdata()" :disabled="isdiable || isubmit">Clear</el-button>

          <el-button type="primary" @click="onChangeproductname()" :disabled="isdiable || isubmit">Search</el-button>

          <el-button type="primary" @click="fenpeimoney()" :disabled="isdiable || isubmit">Update</el-button>
        </div>

        <el-form-item class="cadd">
          <el-table ref="multipleTable" :data="formData.procureditem" prop="procureditem"
            :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" border
            :summary-method="getSummaries" show-summary>
            <el-table-column label="NO" prop="" width="80">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.$index + 1 }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="Refno" width="140" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.ordernumber">{{scope.row.ordernumber}}</span>
                <span v-else>{{scope.row.refno}}</span>
              </template>
            </el-table-column>

            <el-table-column prop="customersid" label="Customer ID" min-width="160" align="center" />

            <el-table-column prop="customername" label="Customer Name" min-width="160" align="center" />

            <el-table-column label="Sales Total" width="140" align="center">
              <template v-slot="scope">
                <span>{{(scope.row.totalamount).toFixed(2)}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Outstanding" width="140" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.outstanding">{{(scope.row.outstanding).toFixed(2)}}</span>
                <span
                  v-else>{{(parseInt(scope.row.totalamount)-parseInt(scope.row.allapayment?scope.row.allapayment:0)).toFixed(2)}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Pay" width="140" align="center">
              <template v-slot="scope">
                <el-button type="primary" plain @click="savepayment(scope.row, scope.$index)"
                  :disabled="scope.row.ispay==1">Pay</el-button>
              </template>
            </el-table-column>

            <el-table-column label="Settle Amount" width="140" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.settleamount" style="width: 65%;" />
              </template>
            </el-table-column>

            <el-table-column label="Settle Discount" width="140" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.settlediscount" style="width: 65%;" />
              </template>
            </el-table-column>

            <el-table-column label="Balance" width="140" align="center">
              <template v-slot="scope">
                <span>{{(parseInt(scope.row.totalamount)-parseInt(scope.row.allapayment?scope.row.allapayment:0)-parseInt(scope.row.settleamount?scope.row.settleamount:0)-parseInt(scope.row.settlediscount?scope.row.settlediscount:0)).toFixed(2)}}</span>
              </template>
            </el-table-column>

          </el-table>


          <el-table :data="tableDatav" size="small" stripe border style="width: 100%;display: none" align="center"
            class="tableDatav">

            <el-table-column label="NO" prop="" width="80">
              <template slot-scope="scope">
                <span>Total</span>
              </template>
            </el-table-column>

            <el-table-column label="Refno" width="140" align="center">
              <template v-slot="scope">
                <span></span>
              </template>
            </el-table-column>

            <el-table-column prop="customersid" label="Customer ID" min-width="160" align="center" />

            <el-table-column prop="customername" label="Customer Name" min-width="160" align="center" />

            <el-table-column label="Sales Total" width="140" align="center">
              <template v-slot="scope">
                <span>{{ salestotal.toFixed(2) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="Outstanding" width="140" align="center">
              <template v-slot="scope">
                <span>{{ totaloutstanding.toFixed(2) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="Pay" width="140" align="center">
              <template v-slot="scope">
                <span></span>
              </template>
            </el-table-column>

            <el-table-column label="Settle Amount" width="140" align="center">
              <template v-slot="scope">
                <span>{{ totalsettleamount.toFixed(2) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="Settle Discount" width="140" align="center">
              <template v-slot="scope">
                <span>{{ totalsettlediscount.toFixed(2) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="Balance" width="140" align="center">
              <template v-slot="scope">
                <span>{{ totalbalance.toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-left: 170px;" v-if="isNew || (isEdit && !isdiable)">
        <el-button plain type="default" @click="close()">Back</el-button>
        <el-button type="primary" @click="saveHandle('ruleForm')" :disabled="isdiable || isubmit">Submit</el-button>

      </div>

    </div>

  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index as customerindex
  } from "@/api/customer";
  import {
    index,
    show,
    update,
    store,
    exportData as exceldata
  } from "@/api/customerpaybackreport";
  import {
    jsPDF
  } from 'jspdf';
  import {
    index as saleinvoiceindex
  } from "@/api/saleinvoice";
  import {
    store as uploadImg
  } from "@/api/medias";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    store as saleinvoicepaymentadd
  } from "@/api/saleinvoicepayment";
  export default {
    name: "stockinadd",
    mixins: [CURD],
    data() {
      return {
        staff: [{
          id: "KW",
          name: "KW",
        }],
        currency: "",
        outstandingbalance: 0,
        billingtitle: [],
        quotationdescriptions: [],
        hoveredIndex: null,
        isubmit: false,
        rowIndex: 0,
        isgoprolist: false,
        ismoney: false,
        isdiable: false,
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          staff: "KW",
          procureditem: [],
        },
        module: "customerpaybackreport",
        newTitle: "New customerpaybackreport",
        editTitle: "Edit customerpaybackreport",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        suppliers: [],
        warehouse: [],
        xiabiao: -1,
        tindex: 0,
        tableData: [],
        customers: [],
        searchForm: {

        },
        printform: {},
        caigou1: false,
        caigou2: false,
        caigou3: false,
        isapproved: false,
        inputElements: [],
        tableDatav: [{
          id: "approved",
          name: "approved",
        }],
      };
    },
    mounted() {

    },
    computed: {
      salestotal() {
        if (this.formData.procureditem) {
          const salestotal = this.formData.procureditem.reduce((total, item) => total + parseFloat(item.totalamount),
            0);
          return salestotal ? salestotal : 0
        }
      },
      totaloutstanding() {
        if (this.formData.procureditem) {
          const totaloutstanding = this.formData.procureditem.reduce((total, item) => total +
            parseInt(item.totalamount) - parseInt(item.allapayment ? item.allapayment : 0),
            0);
          return totaloutstanding ? totaloutstanding : 0
        }
      },
      totalsettleamount() {
        if (this.formData.procureditem) {
          const totalsettleamount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
            .settleamount), 0);
          return totalsettleamount ? totalsettleamount : 0
        }
      },
      totalsettlediscount() {
        if (this.formData.procureditem) {
          const totalsettlediscount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
            .settlediscount), 0);
          return totalsettlediscount ? totalsettlediscount : 0
        }
      },
      totalbalance() {
        if (this.formData.procureditem) {
          const totalbalance = this.formData.procureditem.reduce((total, item) => total +
            parseInt(item.totalamount) - parseInt(item.allapayment ? item.allapayment : 0) - parseInt(item
              .settleamount ?
              item.settleamount : 0) - parseInt(item.settlediscount ? item.settlediscount : 0), 0);
          return totalbalance ? totalbalance : 0
        }
      },
    },
    async created() {
      this.id = this.$route.query.id
      if (this.id > 0) {
        this.isEdit = true
        this.isdiable = true
        const {
          data
        } = await show(this.id);
        this.formData = data;
        this.formData.procureditem = data.procureditem
        if (this.formData.status == "approved") {
          this.isapproved = true
        }
      } else {
        var numStr = "01";
        const {
          data
        } = await index(1, 1);
        var lslist = data;
        if (data.length > 0) {
          var dqskinid = lslist[0].id + 1
          numStr = dqskinid.toString();
        }
        this.isNew = true
        this.isdiable = false

        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const day = currentDate.getDate();
        console.log(`${year}-${month}-${day}`);
        this.formData.addtime = `${year}-${month}-${day}`
        this.formData.ordernumber = "RC" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')
      }

      try {
        const {
          data
        } = await customerindex(1, 100);
        this.customers = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.staff = data.map(item => ({
          id: item.id, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }

    },
    methods: {
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];

        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = 'Total';
            return;
          }






          if (index === 4) {
            const salestotal = data.reduce((total, item) => total + parseFloat(item.totalamount),
              0);
            sums[index] = salestotal ? salestotal : 0
          } else if (index === 5) {
            const totaloutstanding = data.reduce((total, item) => total +
              parseInt(item.totalamount) - parseInt(item.allapayment ? item.allapayment : 0),
              0);
            sums[index] = totaloutstanding ? totaloutstanding : 0
          } else if (index === 7) {
            const totalsettleamount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
              .settleamount), 0);
            sums[index] = totalsettleamount ? totalsettleamount : 0
          } else if (index === 8) {
            const totalsettlediscount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
              .settlediscount), 0);
            sums[index] = totalsettlediscount ? totalsettlediscount : 0
          } else if (index === 9) {
            const totalbalance = this.formData.procureditem.reduce((total, item) => total +
              parseInt(item.totalamount) - parseInt(item.allapayment ? item.allapayment : 0) - parseInt(item
                .settleamount ?
                item.settleamount : 0) - parseInt(item.settlediscount ? item.settlediscount : 0), 0);
            sums[index] = totalbalance ? totalbalance : 0
          } else {
            sums[index] = '';
          }
        });

        return sums;
      },
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;
            try {
              customerindex(1, 100, {
                name: query
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      remoteidMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;
            try {
              customerindex(1, 100, {
                customerid: query
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      async convertExcelToPDF() {
        this.searchForm.id = this.id
        const resv = await exceldata(
          this.page.current_page,
          this.page.per_page,
          this.searchForm);
        const file = new Blob([resv], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        // 读取 Excel 文件
        const reader = new FileReader();
        reader.onload = function(e) {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, {
            type: 'array'
          });

          // 假设只处理第一个 Sheet
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];

          // 将 Sheet 转换为 HTML
          const htmlString = XLSX.utils.sheet_to_html(worksheet);
          const div = document.createElement('div');
          div.innerHTML = htmlString;
          div.style.width = '800px'; // 设置一个足够宽的宽度，以确保内容不会被截断
          div.style.transform = 'scale(0.7)'; // 根据需要调整缩放比例
          div.style.transformOrigin = 'top left'; // 设置变换的原点
          document.body.appendChild(div);

          // 使用 html2canvas 和 jsPDF 转换 HTML 为 PDF
          html2canvas(div).then(canvas => {
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF();
            pdf.addImage(imgData, 'PNG', 0, 0);
            pdf.save('Customer Repayment Report_' + Date.now() + '.pdf');
            document.body.removeChild(div); // 清理 DOM
          });
        };
        reader.readAsArrayBuffer(file);
      },
      async exportData() {
        this.searchForm.id = this.id
        const resv = await exceldata(
          this.page.current_page,
          this.page.per_page,
          this.searchForm);
        this.exportFile('Customer Repayment Report_' + Date.now() + '.xlsx', resv);
      },
      exportFile(fileName, res) {
        const content = res;
        const blob = new Blob([content], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          window.URL.revokeObjectURL(elink.href); // 释放 URL对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          window.navigator.msSaveBlob(blob, fileName);
        }
      },
      async changetermc(value) {
        if (value == 1) {
          const selectedTerm = this.customers.find(item => item.customerid === this.formData.customerid);
          if (selectedTerm) {
            this.formData.currency = selectedTerm.currency
            this.formData.customername = selectedTerm.name
          }
        } else {
          const selectedTerm = this.customers.find(item => item.customerid === this.formData.customername);
          if (selectedTerm) {
            this.formData.currency = selectedTerm.currency
            this.formData.customerid = selectedTerm.customerid
          }
        }
        this.$forceUpdate()
      },
      async savepayment(row, index) {
        if (row.settleamount > 0) {
          const data = {
            saleorders_id: row.id,
            received: row.settleamount,
            recevicetime: this.mydate,
            totalamount: row.totalamount,
            userid: row.customer_id,
          };
          const {
            info
          } = await saleinvoicepaymentadd(data);
          this.$message.success("Edit successfully");
          this.formData.procureditem[index].ispay = 1
          this.$forceUpdate()
          console.log(this.formData.procureditem, "ffff")
        } else {
          this.$message.error("The settleamount must be > 0 ");
        }
      },
      clearformdata() {
        this.formData.remark = ""
        this.formData.paymentamount = ""
        this.formData.paymentdate = ""
        this.formData.customerid = ""
        this.formData.procureditem = []
      },
      fenpeimoney() {
        // if (this.ismoney) {
        //   this.$message.error("The payment amount has been populated");
        //   return false
        // }
        let remainingAmount = parseFloat(this.formData.paymentamount);
        this.formData.procureditem = this.formData.procureditem.map(item => {
          if (remainingAmount > 0) {
            let outstanding = parseFloat(item.totalamount) - parseFloat(item.allapayment || 0);
            let settleAmount = Math.min(outstanding, remainingAmount);
            remainingAmount -= settleAmount;
            return {
              ...item,
              settleamount: (settleAmount).toFixed(2),
              settlediscount: 0
            };
            // settleamount: (parseFloat(item.settleamount || 0) + settleAmount).toFixed(2),
          }
          return item;
        });
        this.ismoney = true
      },
      onCloseDialog() {
        this.caigou1 = false;
        this.caigou2 = false;
        this.caigou3 = false;
      },
      prints(index) {
        if (index == 1) {
          this.caigou1 = true;
        }
        if (index == 2) {
          this.caigou2 = true;
        }
        if (index == 3) {
          this.caigou3 = true;
        }
        this.printform = this.formData;
        console.log(this.printform)
      },

      godisable() {
        this.isdiable = !this.isdiable
      },
      async editstatus(id, statusdata) {
        try {
          await this.$confirm("This operation will permanently Save status. Do you want to continue?", "prompt", {
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
            type: "warning"
          });
          let {
            info
          } = await update({
            id: id,
            action: "status",
            status: statusdata
          });
          this.$message.success("Status update successful");
          this.isapproved = true

          // 刷新当前页
          const {
            data
          } = await show(this.id);
          this.formData = data;
          if (this.formData.status == "approved") {
            this.isapproved = true
          }
          // if (this.formData.status == "rejection") {
          //   this.isdiable = false
          // }



        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled save"
          });
        }
      },

      onChangeproductname() {

        console.log(this.formData.customerid, "customerid")
        console.log(this.formData.customername, 'customeridname')

        if (this.formData.customerid || this.formData.customername) {
          saleinvoiceindex(1, 100, {
            customerid: this.formData.customerid ? this.formData.customerid : this.formData.customername,
            status: "approved"
          }).then(res => {
            this.formData.procureditem = res.data
            for (let i = this.formData.procureditem.length - 1; i >= 0; i--) {
              let item = this.formData.procureditem[i];
              if (item.allapayment >= item.totalamount) {
                this.formData.procureditem.splice(i, 1);
              }
            }
            if (this.formData.procureditem.length > 0) {
              this.formData.staff = this.formData.procureditem[0].staff
            }
          });
        } else {
          this.$message.error("Please input customerid or customername");
        }
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.save(form);
      },
      close() {
        this.$router.push({
          path: '/report/customerpaybackreport'
        });
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {

              this.isubmit = true

              for (let i = this.formData.procureditem.length - 1; i >= 0; i--) {
                let item = this.formData.procureditem[i];
                if (!item.settleamount || item.settleamount === "" || item.settleamount === 0) {
                  this.formData.procureditem.splice(i, 1);
                }
              }


              for (let g = 0; g < this.formData.procureditem.length; g++) {
                let item = this.formData.procureditem[g];
                if (item.ispay != 1) {
                  this.$message.error("Please click pay button");
                  this.isubmit = false
                  return false
                }
              }

              this.formData.customername = this.formData.procureditem[0].customername
              this.formData.receipted = this.formData.procureditem.length
              this.formData.totalsettleamount = this.totalsettleamount

              if (this.formData.staff) {
                const staffinfo = this.staff.find(item => item.name === this.formData.staff);
                if (staffinfo) {
                  this.formData.staffid = staffinfo.id
                }
              }
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/report/customerpaybackreport'
                  });
                }, 1000);
              }

              if (this.isNew) {
                if (this.formData.procureditem != null && this.formData.procureditem.length > 0) {

                } else {
                  this.$message.error("Please add a product");
                  return false
                }
                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                this.$message.success("Add successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/report/customerpaybackreport'
                  });
                }, 1000);

              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.isubmit = false
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.isubmit = false
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
    }
  }
</script>
<style>
  .avatar-uploader {
    position: relative;
  }

  .ordernumber {
    border: 0px;
    text-align: center;
    font-weight: 600;
    position: relative;
    left: 85%;
    display: inline-block;
    top: 94px;
    font-size: 20px;
    height: 30px;
    line-height: 30px;
    width: 170px;
  }

  .bba .el-dialog__body {
    padding: 30px 20px !important;
    color: #606266;
  }

  .customWidth {
    width: 80%;
  }

  .tableDatav .has-gutter {
    display: none;
  }

  .cadd {
    width: 100%;
  }

  .plt {
    position: absolute;
    z-index: 9999;
    left: 170px;
    background: #fff;
  }

  #cadd .el-table th.el-table__cell>.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    font-weight: 600 !important;
    color: #000;
    font-size: 14px !important;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .el-dialog__body {
    padding: 0;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>
